package cn.z;
import cn.aofeng.threadpool4j.ThreadPool;
import cn.aofeng.threadpool4j.ThreadPoolManager;
import cn.aofeng.threadpool4j.handler.DiscardFailHandler;
import cn.aofeng.threadpool4j.handler.LogErrorFailHandler;
import org.apache.log4j.Logger;

import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
/**
 * @author zch
 */
public class ZMain {
	private static Logger myLog = Logger.getLogger(ZMain.class);
	public static void main(String[] args) {
		threadPoolInit();
		ThreadPoolManager tpm = ThreadPoolManager.getSingleton();
		ThreadPool threadPool = tpm.getThreadPool();
		// doJobCallAble(threadPool);
		//		doJobRunnable(threadPool);
		handleSubmitFail(threadPool);
		//		threadPoolDestroy();
	}
	private static void threadPoolInit() {
		ThreadPoolManager tpm = ThreadPoolManager.getSingleton();
		tpm.init();
	}
	private static void threadPoolDestroy() {
		ThreadPoolManager tpm = ThreadPoolManager.getSingleton();
		tpm.destroy();
	}
	private static void doJobCallAble(ThreadPool threadPool) {
		int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
		CallableAnnyTask task = new CallableAnnyTask(arr);
		Future<Long> future = threadPool.submit(task);
		// 将异步任务交给默认的线程池default执行
		try {
			System.out.println("异步任务在线程池default的执行结果为:" + future.get());
			// 将异步任务交给指定的线程池other执行
			threadPool.submit(task, "me");
			System.out.println("异步任务在线程池other的执行结果为:" + future.get());
		}
		catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
	}
	private static void doJobRunnable(ThreadPool threadPool) {
		// 未指定线程池名称时，任务会提交到名为"default"的线程池执行
		threadPool.submit(new RunnableAsynTask());
		// 将task2提交到名为"other"的线程池执行
		threadPool.submit(new RunnableAsynTask(), "me");
	}
	private static void handleSubmitFail(ThreadPool threadPool) {
		// 队列满时，提交失败的任务直接丢弃
		for (int i = 0; i < 30; i++) {
			System.out.println("提交AA：" + i+" "+threadPool.getThreadPoolInfo("default"));
			threadPool.submit(new cn.aofeng.example.RunnableAsynTask(i), "default", new DiscardFailHandler<Runnable>());
			System.out.println("提交AA：" + i);
		}
		try {
			System.out.println("开始等待" + new Date());
			Thread.sleep(10000);
			System.out.println("等待结束" + new Date());
		}
		catch (InterruptedException e) {
			e.printStackTrace();
		}
		for (int i = 0; i < 30; i++) {
			myLog.error("提交BA：" + i * 10);
			threadPool.submit(new cn.aofeng.example.RunnableAsynTask(i * 10), "default", new LogErrorFailHandler<Runnable>());
		}
		//				for (int i = 0; i < 30; i++) {
		//					myLog.error("提交BA：" + i);
		//					Future future2 = threadPool.submit(new cn.aofeng.example.RunnableAsynTask(i), "default", new LogErrorFailHandler<Runnable>());
		//					try {
		//						myLog.error("提交BB：" + i + " " + future2.get());
		//					}
		//					catch (InterruptedException | ExecutionException e) {
		//						e.printStackTrace();
		//					}
		//				}
	}
}
